package bepviet.android.engine;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;

public class handleImage {
	
	public static ByteArrayOutputStream byteArray(Bitmap src) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		src.compress(CompressFormat.PNG, 0, bos);
		return bos;
	}
	
	
	public static byte[] toHex(String selectedImage){		
			//Bitmap bitmap = decodeUri(selectedImage);
			Bitmap bitmap = Url(selectedImage);
			byte[] buffer = byteArray(bitmap).toByteArray();
			return buffer;		
	}
	
	
	private static Bitmap Url(String selectedImage){
		// Get the stream 

		InputStream input;
		try {
			input = new FileInputStream(new File(selectedImage));
		} catch (FileNotFoundException e) {
			input = null;
			e.printStackTrace();
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
	      options.inSampleSize=8;
	      Bitmap tempBitmap = BitmapFactory.decodeStream(input, null, options);
	      return tempBitmap;
	}
	
	
	private static Bitmap decodeUri(String selectedImage) {

		InputStream input;
		try {
			input = new FileInputStream(new File(selectedImage));
		} catch (FileNotFoundException e) {
			input = null;
			e.printStackTrace();
		}
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(input, null, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 140;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
        if (width_tmp / 2 < REQUIRED_SIZE
            || height_tmp / 2 < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(input, null, o2);

    }
}
